﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using AlipaySDK.Alipay;
using AlipaySDK.Dto.Payment;

namespace AlipaySDK.Helper
{
    public class WapPayment
    {
        /// <summary>
        /// 组成支付宝网页支付的html
        /// </summary>
        /// <param name="request"><see cref="ComposeWapPayRequest"/></param>
        /// <returns></returns>
        public static ComposeWapPayResponse ComposeWapPayParameter(ComposeWapPayRequest request)
        {
            //支付宝网关地址
            string GATEWAY_NEW = "http://wappaygw.alipay.com/service/rest.htm?";
            string format = "xml";
            string v = "2.0";
            string req_id = DateTime.Now.ToString("yyyyMMddHHmmss");
            string notify_url = request.NotifyUrl;
            string call_back_url = request.CallBackUrl;
            string merchant_url = request.MerchantUrl;
            string seller_email = AlipayConfig.SellerEmail; //Config.SellEmail;
            string out_trade_no = request.OutTradeNo;
            string subject = request.Subject;
            string total_fee = request.TotalFee;
            string req_dataToken = "<direct_trade_create_req>";//
            if (notify_url != "")
                req_dataToken += "<notify_url>" + notify_url + "</notify_url>";
            if (call_back_url != "")
                req_dataToken += "<call_back_url>" + call_back_url + "</call_back_url>";
            req_dataToken += "<seller_account_name>" + seller_email + "</seller_account_name><out_trade_no>" + out_trade_no + "</out_trade_no><subject>" + subject + "</subject><total_fee>" + total_fee + "</total_fee>";
            if (merchant_url != "")
                req_dataToken += "<merchant_url>" + merchant_url + "</merchant_url>";
            req_dataToken += "</direct_trade_create_req>";
            //"<direct_trade_create_req><notify_url>" + notify_url + "</notify_url><call_back_url>" + call_back_url + "</call_back_url><seller_account_name>" + seller_email + "</seller_account_name><out_trade_no>" + out_trade_no + "</out_trade_no><subject>" + subject + "</subject><total_fee>" + total_fee + "</total_fee><merchant_url>" + merchant_url + "</merchant_url></direct_trade_create_req>";
            //把请求参数打包成数组
            Dictionary<string, string> sParaTempToken = new Dictionary<string, string>();
            sParaTempToken.Add("partner", AlipayConfig.pid);
            sParaTempToken.Add("_input_charset", "utf-8");
            sParaTempToken.Add("sec_id", AlipayConfig.SignType.ToUpper());
            sParaTempToken.Add("service", "alipay.wap.trade.create.direct");
            sParaTempToken.Add("format", format);
            sParaTempToken.Add("v", v);
            sParaTempToken.Add("req_id", req_id);
            sParaTempToken.Add("req_data", req_dataToken);
            Submit sm = new Submit(AlipayConfig.pid, AlipayConfig.AliPayKey, AlipayConfig.WapRSAPrivateKey, "utf-8", AlipayConfig.SignType);
            //建立请求
            string sHtmlTextToken = sm.BuildRequest(GATEWAY_NEW, sParaTempToken);
            //URLDECODE返回的信息
            Encoding code = Encoding.GetEncoding("utf-8");
            sHtmlTextToken = System.Net.WebUtility.UrlDecode(sHtmlTextToken);

            //解析远程模拟提交后返回的信息
            Dictionary<string, string> dicHtmlTextToken = sm.ParseResponse(sHtmlTextToken);
            //获取token
            string request_token = dicHtmlTextToken["request_token"];
            //业务详细
            string req_data = "<auth_and_execute_req><request_token>" + request_token + "</request_token></auth_and_execute_req>";
            //必填

            //把请求参数打包成数组
            Dictionary<string, string> sParaTemp = new Dictionary<string, string>();
            sParaTemp.Add("partner", AlipayConfig.pid);
            sParaTemp.Add("_input_charset", "utf-8");
            sParaTemp.Add("sec_id", AlipayConfig.SignType.ToUpper());
            sParaTemp.Add("service", "alipay.wap.auth.authAndExecute");
            sParaTemp.Add("format", format);
            sParaTemp.Add("v", v);
            sParaTemp.Add("req_data", req_data);
            //建立请求
            string sHtmlText = sm.BuildRequest(GATEWAY_NEW, sParaTemp, "get", "确认");

            return new ComposeWapPayResponse
            {
                ResultCode = "0",
                ResultMsg = "成功",
                RequestHtml = sHtmlText
            };
        }

        /// <summary>
        /// 支付宝退款
        /// </summary>
        /// <param name="request"><see cref="WapPayRefundRequest"/></param>
        /// <returns></returns>
        public static WapPayRefundResponse WapPayRefund(WapPayRefundRequest request)
        {
            //支付宝网关地址
            string GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
            //把请求参数打包成数组
            Dictionary<string, string> sParaTemp = new Dictionary<string, string>();
            sParaTemp.Add("partner", AlipayConfig.pid);
            sParaTemp.Add("_input_charset", "utf-8");
            sParaTemp.Add("service", "refund_fastpay_by_platform_nopwd");
            sParaTemp.Add("notify_url", request.NotifyUrl);
            sParaTemp.Add("batch_no", request.BatchNo);
            sParaTemp.Add("refund_date", request.RefundDate);
            sParaTemp.Add("batch_num", request.BatchNum);
            sParaTemp.Add("detail_data", request.DetailData);
            //建立请求
            Submit sm = new Submit(AlipayConfig.pid, AlipayConfig.PartnerAliPayPublicKey, AlipayConfig.PartnerRSAPrivateKey, "utf-8", "RSA");
            //建立请求
            string sHtmlText = sm.BuildRequest(GATEWAY_NEW, sParaTemp);

            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.LoadXml(sHtmlText);
                string is_success = xmlDoc.SelectSingleNode("/alipay/is_success")?.InnerText;
                return new WapPayRefundResponse
                {
                    ResultCode = "0",
                    ResultMsg = "成功",
                    IsSuccess = is_success
                };
            }
            catch (Exception exp)
            {
                return new WapPayRefundResponse
                {
                    ResultCode = "1",
                    ResultMsg = exp.Message
                };
            }
        }


        /// <summary>
        /// 支付宝通知结果验签
        /// </summary>
        /// <param name="request"><see cref="WapPayVerifyNotifyRequest"/></param>
        /// <returns></returns>
        public static WapPayVerifyNotifyResponse WapPayVerifyNotify(WapPayVerifyNotifyRequest request)
        {
            //Dictionary<string, string> sPara = request.SPara;
            string sign = request.Sign;

            Notify aliNotify = new Notify(AlipayConfig.pid, AlipayConfig.AliPayKey, AlipayConfig.WapRSAPrivateKey, AlipayConfig.WapAliPayPublicKey, "utf-8", AlipayConfig.SignType);
            Dictionary<string, string> inputPara = request.SPara;
            try
            {
                //inputPara = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(sPara);
                if (inputPara != null && inputPara.Count > 0 && aliNotify.VerifyNotify(inputPara, sign))
                {
                    inputPara = aliNotify.Decrypt(inputPara);
                    return new WapPayVerifyNotifyResponse
                    {
                        ResultCode = "0",
                        ResultMsg = "成功",
                        NotifyData = inputPara["notify_data"] ?? inputPara["batch_no"]
                    };
                }
                else
                {
                    return new WapPayVerifyNotifyResponse
                    {
                        ResultCode = "1",
                        ResultMsg = "验签失败"
                    };
                }
            }
            catch (Exception ee)
            {
                return new WapPayVerifyNotifyResponse
                {
                    ResultCode = "1",
                    ResultMsg = ee.Message
                };
            }

        }


        /// <summary>
        /// 支付宝交易查询
        /// </summary>
        /// <param name="request" ><see cref="WapPayQueryRequest"/></param>
        /// <returns></returns>
        public static WapPayQueryResponse WapPayQuery(WapPayQueryRequest request)
        {
            //支付宝网关地址
            string GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
            //把请求参数打包成数组
            Dictionary<string, string> sParaTemp = new Dictionary<string, string>();
            sParaTemp.Add("partner", AlipayConfig.pid);
            sParaTemp.Add("_input_charset", "utf-8");
            sParaTemp.Add("service", "single_trade_query");
            sParaTemp.Add("trade_no", request.TradeNo);
            sParaTemp.Add("out_trade_no", request.OutTradeNo);
            //建立请求
            Submit sm = new Submit(AlipayConfig.pid, AlipayConfig.AliPayKey, AlipayConfig.WapRSAPrivateKey, "utf-8", "RSA");
            //建立请求
            string sHtmlText = sm.BuildRequest(GATEWAY_NEW, sParaTemp);
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.LoadXml(sHtmlText);
                string isSuccess = xmlDoc.SelectSingleNode("/alipay/is_success")?.InnerText;
                string tradeStatus = xmlDoc.SelectSingleNode("/alipay/response/trade/trade_status")?.InnerText;
                return new WapPayQueryResponse()
                {
                    ResultCode = "0",
                    ResultMsg = "成功",
                    IsSuccess = isSuccess,
                    TradeStatu = tradeStatus
                };
            }
            catch (Exception exp)
            {
                return new WapPayQueryResponse
                {
                    ResultCode = "1",
                    ResultMsg = exp.Message
                };
            }
        }

    }
}
